package com.besttone.locate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class BMapActivity extends Activity {
	final static String TAG = "MapActivty";
	//BMapManager mBMapMan = null;
    public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	public MKMapViewListener mMapListener = null;
	public MKMapViewListener mLocListener = null;
	static MapView mMapView = null;
	private MapController mMapController = null;
	private View popView;
	
	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
    public NotifyLister mNotifyer=null;
	LocationData locData = null;
	MyLocationOverlay myLocationOverlay = null;
	
	Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            //Toast.makeText(BMapActivity.this, "msg:" +msg.what, Toast.LENGTH_SHORT).show();
        };
    };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
		//mBMapMan = new BMapManager(getApplication());

        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(app.strKey,new BMapApiDemoApp.MyGeneralListener());
        }
		
		// 注意：请在试用setContentView前初始化BMapManager对象，否则会报错
		setContentView(R.layout.map);
		mMapView = (MapView) findViewById(R.id.bmapsView);
		// 设置启用内置的缩放控件
		mMapController = mMapView.getController();
		
        initMapView();
		
		initLocView();
		
        //更新本机定位
        testUpdateClick();
        
        //准备数据
        GeoPoint point = prepairData();
        
        // 添加ItemizedOverlay
        testItemClick(point);
	}
	
    private void initLocView() {
        mLocClient = new LocationClient( this );
        mLocClient.registerLocationListener( myListener );
        
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.setScanSpan(60000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        
        mLocListener = new MKMapViewListener() {
			
			@Override
			public void onMapMoveFinish() {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(BMapActivity.this,title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onMapAnimationFinish() {
				// TODO Auto-generated method stub
				
			}
		};
		mMapView.regMapViewListener(BMapApiDemoApp.getInstance().mBMapManager, mLocListener);
    	
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
	    myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
    }
	
	
    private void initMapView() {
        mMapListener = new MKMapViewListener() {
			
			@Override
			public void onMapMoveFinish() {
			}
			
			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(BMapActivity.this,title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
			}

			@Override
			public void onMapAnimationFinish() {
			}
		};
		mMapView.regMapViewListener(BMapApiDemoApp.getInstance().mBMapManager, mMapListener);
		
        mMapView.setBuiltInZoomControls(true);
        mMapView.setDoubleClickZooming(true);
        mMapView.setOnTouchListener(null);
        mMapView.setLongClickable(true);
        
		mMapController.setZoom(14);// 设置地图zoom级别
        mMapController.enableClick(true);
    }
    
	private GeoPoint prepairData() {
		GeoPoint point = null;
		Bundle bundle = this.getIntent().getExtras();
		double lng = Double.valueOf(bundle.getString("lng"));
		double lat = Double.valueOf(bundle.getString("lat"));
		// 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
		point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
		
	    OverlayItem item = new OverlayItem(point, "", "");
	    mGeoList.add(item);
		
		return point;
	}
    
    public void testItemClick(GeoPoint point) {
    	Drawable marker = BMapActivity.this.getResources().getDrawable(R.drawable.icon_marka);
	    //mMapView.getOverlays().clear();
	    OverlayTest ov = new OverlayTest(marker, this);
	    for(OverlayItem item : mGeoList){
	    	ov.addItem(item);
	    }
	    mMapView.getOverlays().add(ov);
	    
		mMapController.setCenter(point);// 设置地图中心点
        
	    mMapView.refresh();
   }
    
    public void testUpdateClick(){
        mLocClient.requestLocation();
    }
    
	private void initPopview(){
    	popView = super.getLayoutInflater().inflate(R.layout.pop, null);
    	mMapView.addView( popView,
              new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT,
            null, MapView.LayoutParams.BOTTOM_CENTER));
           //由于气泡的尾巴是在下边居中的,因此要设置成MapView.LayoutParams.BOTTOM_CENTER.
           //这里没有给GeoPoint,在onFocusChangeListener中设置
//        views.add(popView);
       popView.setVisibility(View.GONE);

    }
	
	

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
        if (mLocClient != null)
            mLocClient.stop();
        mMapView.destroy();
        super.onDestroy();
    }
    
	/**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return ;
            
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            myLocationOverlay.setData(locData);
            mMapView.refresh();
            //mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)), mHandler.obtainMessage(1));
        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
    
    public class NotifyLister extends BDNotifyListener{
        public void onNotify(BDLocation mlocation, float distance) {
        }
    }

}

class OverlayTest extends ItemizedOverlay<OverlayItem> {
	private Context mContext = null;
    static PopupOverlay pop = null;
    public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
    Toast mToast = null;
    
	public OverlayTest(Drawable marker,Context context){
		super(marker);
		this.mContext = context;
        pop = new PopupOverlay(BMapActivity.mMapView, new PopupClickListener() {
			
			@Override
			public void onClickedPopup(int index) {
			    if (null == mToast)
			        mToast = Toast.makeText(mContext, "popup item :" + index + " is clicked.", Toast.LENGTH_SHORT);
			    else mToast.setText("popup item :" + index + " is clicked.");
			    mToast.show();
			}
		});
	    populate();
		
	}
	protected boolean onTap(int index) {
        Bitmap[] bmps = new Bitmap[3];
        try {
            bmps[0] = BitmapFactory.decodeStream(mContext.getAssets().open("marker1.png"));
            bmps[1] = BitmapFactory.decodeStream(mContext.getAssets().open("marker2.png"));
            bmps[2] = BitmapFactory.decodeStream(mContext.getAssets().open("marker3.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
	    pop.showPopup(bmps, mGeoList.get(index).getPoint(), 32);
//		if (null == mToast)
//            mToast = Toast.makeText(mContext, mGeoList.get(index).getTitle(), Toast.LENGTH_SHORT);
//        else mToast.setText(mGeoList.get(index).getTitle());
//		mToast.show();
		
		return true;
	}
	public boolean onTap(GeoPoint pt, MapView mapView){
		if (pop != null){
			pop.hidePop();
		}
		super.onTap(pt,mapView);
		return false;
	}
	
	@Override
	protected OverlayItem createItem(int i) {
		return mGeoList.get(i);
	}
	
	@Override
	public int size() {
		return mGeoList.size();
	}
	public void addItem(OverlayItem item){
		mGeoList.add(item);
		populate();
	}
	public void removeItem(int index){
		mGeoList.remove(index);
		populate();
	}

	
}


